<template>
  <div class="login-wrap">
    <div class="login-left">
      <img class="login-img" src="~@/assets/login-logo.png" />
      <div class="login-text">
        <span class="title">高效能数据中心调度</span>
        <!-- <span class="subtitle">关键技术与装备</span> -->
      </div>
    </div>
    <div class="login-right">
      <h2>用户登录</h2>
      <a-form :form="form" class="user-layout-login" ref="formLogin" id="formLogin">
        <a-form-item>
          <a-input size="large"
            v-decorator="['username', validatorRules.username, { validator: this.handleUsernameOrEmail }]" type="text"
            placeholder="请输入帐户名">
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-item>

        <a-form-item>
          <a-input v-decorator="['password', validatorRules.password]" size="large" type="password" autocomplete="false"
            placeholder="密码">
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-item>
        <br />
        <!-- <a-form-item>
          <a-checkbox v-decorator="['rememberMe', { initialValue: true, valuePropName: 'checked' }]">自动登陆</a-checkbox>
          <router-link :to="{ name: 'login' }" class="forge-password" style="float: right"> 忘记密码 </router-link> -->
          <!-- <router-link :to="{ name: 'register' }" class="forge-password" style="float: right; margin-right: 10px">
            注册账户
          </router-link> -->
        <!-- </a-form-item> -->

        <a-form-item style="margin-top: 24px">
          <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="loginBtn"
            @click.stop.prevent="handleSubmit" :disabled="loginBtn"
            style="background-color: rgb(0,150,136);border-color: rgb(0,150,136);">确定</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
  // import api from '@/api'
  import {
    mapActions
  } from 'vuex'
  import Vue from 'vue'
  import {
    ACCESS_TOKEN,
  } from '@/store/mutation-types'
  import store from '@/store/'

  export default {
    data() {
      return {
        loginBtn: false,
        form: this.$form.createForm(this),
        validatorRules: {
          username: {
            rules: [{
              required: true,
              message: '请输入用户名!'
            }, {
              validator: this.handleUsernameOrEmail
            }],
            initialValue: ''
          },
          password: {
            rules: [{
              required: true,
              message: '请输入密码!',
              validator: 'click'
            }],
            initialValue: ''
          },
        },
        currdatetime: '',
      }
    },
    created() {
      this.getRouterData()
      this.currdatetime = new Date().getTime()
      Vue.ls.remove(ACCESS_TOKEN)
    },
    methods: {
      ...mapActions(['Login', 'Logout', 'PhoneLogin', 'ThirdLogin']),
      //第三方登录
      onThirdLogin(source) {
        // let url = window._CONFIG['domianURL'] + `/thirdLogin/render/${source}`
        let url = `/thirdLogin/render/${source}`
        window.open(
          url,
          `login ${source}`,
          'height=500, width=500, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no'
        )
        let that = this
        let receiveMessage = function (event) {
          var origin = event.origin
          // console.log('origin', origin)

          let token = event.data
          // console.log('event.data', token)
          that.ThirdLogin(token).then((res) => {
            if (res.success) {
              that.loginSuccess()
            } else {
              that.requestFailed(res)
            }
          })
        }
        window.addEventListener('message', receiveMessage, false)
      },
      // handler
      handleUsernameOrEmail(rule, value, callback) {
        const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
        callback()
      },
      handleSubmit() {
        let that = this
        let loginParams = {}
        that.loginBtn = true
        // 使用账户密码登陆
        that.form.validateFields(
          ['username', 'password', 'rememberMe'], {
            force: true
          },
          (err, values) => {
            if (!err) {
              loginParams.username = values.username
              loginParams.password = values.password
              loginParams.remember_me = values.rememberMe
              loginParams.checkKey = that.currdatetime
              that
                .Login(loginParams)
                .then((res) => {
                  that.loginSuccess()
                })
                .catch((err) => {
                  that.requestFailed(err)
                })
            } else {
              that.loginBtn = false
            }
          }
        )
      },
      loginSuccess() {
        // update-begin- author:sunjianlei --- date:20190812 --- for: 登录成功后不解除禁用按钮，防止多次点击
        // this.loginBtn = false
        // update-end- author:sunjianlei --- date:20190812 --- for: 登录成功后不解除禁用按钮，防止多次点击
        this.$router.push({
          path: '/dashboard/analysis'
        }).catch(() => {
          // console.log('登录跳转首页出错,这个错误从哪里来的')
        })
      },
      cmsFailed(err) {
        this.$notification['error']({
          message: '登录失败',
          description: err,
          duration: 4,
        })
      },
      requestFailed(err) {
        this.$notification['error']({
          message: '登录失败',
          description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
          duration: 4,
        })
        this.loginBtn = false
      },
      validateMobile(rule, value, callback) {
        if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
          callback()
        } else {
          callback('您的手机号码格式不正确!')
        }
      },
      getRouterData() {
        this.$nextTick(() => {
          if (this.$route.params.username) {
            this.form.setFieldsValue({
              username: this.$route.params.username,
            })
          }
        })
      },
    },
  }
</script>

<style lang="less" scoped>
  .user-layout-login {
    label {
      font-size: 14px;
    }

    .forge-password {
      font-size: 14px;
    }

    button.login-button {
      padding: 0 15px;
      font-size: 16px;
      height: 40px;
      width: 100%;
    }

    .user-login-other {
      text-align: left;
      margin-top: 24px;
      line-height: 22px;

      .item-icon {
        font-size: 24px;
        color: rgba(0, 0, 0, 0.2);
        margin-left: 16px;
        vertical-align: middle;
        cursor: pointer;
        transition: color 0.3s;

        &:hover {
          color: #1890ff;
        }
      }

      .register {
        float: right;
      }
    }
  }

  .login-wrap {
    .login-left {
      display: inline-block;
      width: 50%;
      text-align: right;
      padding-right: 15px;

      .login-img {
        display: inline-block;
        width: 120px;
        height: 120px;
      }

      .login-text {
        margin-left: 20px;
        color: white;
        display: inline-block;
        vertical-align: bottom;
        margin-right: 6%;

        span {
          display: block;
          text-align: left;
        }

        .title {
          font-size: 40px;
          line-height: 120px;
          font-weight: bold;
        }

        .subtitle {
          font-size: 20px;
          margin-bottom: 6px;
          margin-top: 15px;
        }
      }
    }

    .login-right {
      h2 {
        text-align: center;
        padding-bottom: 10px;
      }

      display: inline-block;
      background-color: rgb(242, 242, 242);
      position: relative;
      margin-left: 10%;
      top: 100px;
      padding: 25px 40px 10px;
    }
  }
</style>
<style>
  .valid-error .ant-select-selection__placeholder {
    color: #f5222d;
  }
</style>